import json
from flask import current_app
from aliyunsdkcore.client import AcsClient
from aliyunsdkvod.request.v20170321 import (
    CreateUploadVideoRequest,
    RefreshUploadVideoRequest,
    GetPlayInfoRequest
)

from .voduploadsdk.AliyunVodUtils import *
from .voduploadsdk.AliyunVodUploader import AliyunVodUploader
from .voduploadsdk.UploadVideoRequest import UploadVideoRequest 
# 测试上传本地视频
def uploadLocalVideo(accessKeyId, accessKeySecret, filePath):
    try:
        uploader = AliyunVodUploader(accessKeyId, accessKeySecret)
        uploadVideoRequest = UploadVideoRequest(filePath, 'test upload local video')
        # 可以设置视频封面，如果是本地或网络图片可使用UploadImageRequest上传图片到点播，获取到ImageURL
        #uploadVideoRequest.setCoverURL('https://sample.com/sample.jpg')  
        #uploadVideoRequest.setTags('test1,test2')
        videoId = uploader.uploadLocalVideo(uploadVideoRequest)
        print("file: %s, videoId: %s" % (filePath, videoId))
    except AliyunVodException as e:
        print(e)
        
    return videoId


# 初始化，返还clt客户端
def init_vod_client(accessKeyId, accessKeySecret):
    regionId = 'cn-shanghai'   # 点播服务接入区域
    connectTimeout = 3         # 连接超时，单位为秒
    return AcsClient(
        accessKeyId,
        accessKeySecret,
        regionId,
        auto_retry=True,
        max_retry_time=3,
        timeout=connectTimeout
    )


# 获取视频上传地址和凭证，返还uploadInfo，有videoId！
def create_upload_video(clt, videoInfo):
    request = CreateUploadVideoRequest.CreateUploadVideoRequest()
    request.set_Title(videoInfo['videoTitle'])   # 设置视频的标题
    # 视频在本地存放的地址 如；/opt/video/sample/video_file.mp4
    request.set_FileName(videoInfo['videoAddress'])
    # request.set_Description(videoInfo['videoDescription'])  # 视频描述
    # request.set_CoverURL(videoInfo['coverUrl'])  # 视频封面如：http://img.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-700.png
    # request.set_Tags(videoInfo['tags'])  # 视频标签如："动漫，表白" "tag1,tag2"
    request.set_CateId(0)
    request.set_accept_format('JSON')  # 设置接收数据未JSON
    response = json.loads(clt.do_action_with_exception(request).decode())

    return response


# 视频文件上传超时后重新获取上传凭证
# 刷新视频上传凭证，返还UploadAuth上传凭证；UploadAddress上传地址
def refresh_upload_video(clt, videoId):
    request = RefreshUploadVideoRequest.RefreshUploadVideoRequest()
    request.set_VideoId(videoId)
    request.set_accept_format('JSON')
    return json.loads(clt.do_action_with_exception(request).decode())


# 获取播放地址, 返还:
# VideoBase	视频基本信息。
# PlayInfoList 视频流信息列表。
def get_play_info(clt, videoId):
    request = GetPlayInfoRequest.GetPlayInfoRequest()
    request.set_accept_format('JSON')
    request.set_VideoId(videoId)
    request.set_AuthTimeout(3600*5)
    response = json.loads(clt.do_action_with_exception(request).decode())
    return response
